package com.halflife.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SelectorServer {
    private ServerSocketChannel server = null;
    private Selector selector = null;
    int port = 9090;

    public void initServer() {
        try {
            server = ServerSocketChannel.open();
            server.configureBlocking(false);
            server.bind(new InetSocketAddress(port));

            selector = Selector.open();
            server.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException EX) {
        }
    }

    public void start() throws Exception{
        initServer();
        System.out.println("启动");
        while (true) {
            /**
             * 0 阻塞等待
             */
            while (selector.select(0)>0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iter = selectionKeys.iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
//                    iter.remove();
                    if (key.isAcceptable()) {
                        ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                        SocketChannel client = ssc.accept();
                        client.configureBlocking(false);
                        ByteBuffer byteBuffer = ByteBuffer.allocate(8096);
                        client.register(selector, SelectionKey.OP_READ, byteBuffer);
                        System.out.println("====================");
                        System.out.println("新客户端:"+client.getRemoteAddress());
                        System.out.println("====================");
                    } else if (key.isReadable()) {
                        SocketChannel client = (SocketChannel) key.channel();
                        ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
                        byteBuffer.clear();
                        client.read(byteBuffer);
                        byteBuffer.flip();
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        SelectorServer selectorServer = new SelectorServer();
        selectorServer.start();
    }

}
